package me.j360.springboot.simple.interceptors;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with springbootweb -> me.j360.springboot.simple.web.filter.
 * User: min_xu
 * Date: 2015/7/30
 * Time: 15:27
 * 说明：
 */
public class J360UrlInterceptor implements HandlerInterceptor {

    public J360UrlInterceptor(){
        System.out.println("--------------- TestUrlInterceptor initialize -------------");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if(request.getRequestURI().equals("/error")){
            System.out.println("------------------error path");
            //request.getRequestDispatcher("/invalidPage");
            response.sendRedirect("/invalidPage");
        }
        System.out.println("--------------TestUrlInterceptor work-----------------" + request.getRequestURI());

        return true;
    }

    /**
     * This implementation is empty.
     */
    @Override
    public void postHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {

        if(modelAndView == null){
            modelAndView = new ModelAndView("error");
            throw new Exception("not find this path!!!!!");
        }
        System.out.println("-------------- TestUrlInterceptor post url -----------------" + modelAndView.getViewName());
    }

    /**
     * This implementation is empty.
     */
    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        if(ex != null){
            System.out.println("-------------- TestUrlInterceptor completion -----------------" + ex.getMessage());
        }
    }
}